var express = require("express");
var router = express.Router();
var moment = require("moment");

var Web3 = require("web3");
var web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));

var abi = [
    {
        "constant": true,
        "inputs": [
            {
                "name": "_id",
                "type": "string"
            },
            {
                "name": "_currentDate",
                "type": "uint32"
            }
        ],
        "name": "legal",
        "outputs": [
            {
                "name": "",
                "type": "bool"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "_addr",
                "type": "address"
            }
        ],
        "name": "setAddr",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [
            {
                "name": "_citizenAddr",
                "type": "address"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    }
];
var contractAddr = "0x836e1017706a6d94d62ac22f33c6f4dfc89b08aa";
var contract = new web3.eth.Contract(abi, contractAddr);

function unlock(address, password,callback) {
    web3.eth.personal.unlockAccount(address,password,function(error,result){
        if(result) {
            callback();
        }
    })
}
router.get("/legal", function (req, resp) {
    var account = "0x1ef156e09d67d85dd4f660ccb67c4703d1395eef";
    unlock(account,"123",function (error,result) {
        var date = moment().format("YYYYMMDD");
        var dateNumber = +date;
        var id = req.query.id;
        //console.log(id);
        contract.methods.legal(id,dateNumber).call({
            from: account
        }).then(function (result) {
            resp.send(result);
        });
    })



});

module.exports = router;